package com.example.administrator.yuejian_2.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.yuejian_2.R;
import com.example.administrator.yuejian_2.bean.PostAddBean;
import com.example.administrator.yuejian_2.interservice.Const;
import com.example.administrator.yuejian_2.interservice.PostService;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PostAddActivity extends AppCompatActivity {
    private ImageButton backButton;
    private ImageButton addpic;
    private Button addButton;
    private ImageView img1;
    private EditText title;
    private static String path ;
    private int uid;
    /* tinajia*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_postadd);

        SharedPreferences sharedPreferences = getSharedPreferences("userInfo",
                Context.MODE_PRIVATE);
        uid = sharedPreferences.getInt("user_id",0);

        title = (EditText) findViewById(R.id.postadd_content);
        backButton = (ImageButton) findViewById(R.id.back_imageButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        img1 = (ImageView) findViewById(R.id.img1);

        addpic = (ImageButton) findViewById(R.id.imageButton5);
        addpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(intent,1);
            }
        });
        addButton = (Button) findViewById(R.id.postadd_button);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadImage();
            }
        });
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            if (data != null) {
                img1.setImageURI(data.getData());
            }
        }
        Bitmap bitmap = null;
        ContentResolver resolver = getContentResolver();
        if (requestCode == 1) {
            Uri uri = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(resolver, uri);//获得图片
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        img1.setImageBitmap(bitmap);

        if (requestCode == 1) {

            Uri uri = data.getData();


            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }


            if (DocumentsContract.isDocumentUri(this,uri)) {
                System.out.println("sssssssssssssss");
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    System.out.println("aaaaaaaaaaaaa");
                    String docId = DocumentsContract.getDocumentId(uri);
                    String id = docId.split(":")[1]; // 解析出数字格式的id
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    // imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

                    Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            null, selection, null, null);
                    if (cursor != null) {
                        if (cursor.moveToFirst()) {
                            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                            //   System.out.println(path);
                        }
                        cursor.close();
                    }
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    System.out.println("bbbbbbbbbbbbbbbbbbbb");
                }
            }
        }
    }



    private void uploadImage() {

        File file = new File(path);
        MediaType textType = MediaType.parse("text/plain");
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", path, requestFile);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Const.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService service = retrofit.create(PostService.class);
        Call<PostAddBean> call = service.ShaituAdd(uid,title.getText().toString(),filePart);
        call.enqueue(new Callback<PostAddBean>() {
            @Override
            public void onResponse(Call<PostAddBean> call, Response<PostAddBean> response) {
                Toast.makeText(PostAddActivity.this, "成功", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<PostAddBean> call, Throwable t) {
                Toast.makeText(PostAddActivity.this, "失败", Toast.LENGTH_LONG).show();

            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        Log.d("TAG", "requestCode=" + requestCode + "; --->" + permissions.toString()
                + "; grantResult=" + grantResults.toString());
        switch (requestCode) {
            case 0: {

                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                }

                return;
            }
            default:
                break;

        }
    }


}
